package dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 获取Connection和释放Connection的类
 * Created by jcala on 2016/3/15.
 */
public class JDBCTools {
    /**
     * C3P0数据库连接池的一些配置操作
     * @return C3P0的ComboPooledDataSource
     */
    protected static ComboPooledDataSource getDataSource(){
        ComboPooledDataSource dataSource= null;
        try {
            dataSource = null;
            dataSource=new ComboPooledDataSource();
            dataSource.setUser( "id ");
            dataSource.setPassword( "pw ");
            dataSource.setJdbcUrl( "jdbc:mysql://127.0.0.1:3306/anqi? autoReconnect=true&useUnicode=true&characterEncoding=utf-8 ");
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setInitialPoolSize(10);
            dataSource.setMinPoolSize(1);
            dataSource.setMaxPoolSize(100);
            dataSource.setMaxStatements(50);
            dataSource.setMaxIdleTime(60);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        } finally {
            if(dataSource!=null){
                dataSource.close();
            }
        }
        return dataSource;
    }

    /**
     *通过C3P0的ComboPooledDataSource获取数据库连接
     * @return 数据库连接Connection
     */
    protected static Connection getConn() {
        Connection conn=null;
        try {
            conn=getDataSource().getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseConn(conn,null,null);
        }
        return conn;
    }

    /**
     * 释放数据库一些资源
     */
    protected static void releaseConn(Connection conn,Statement st,ResultSet rs){
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
